package com.twu.biblioteca;

public class LoginController extends AbstractController {

    private String username;

    private UserRepository userRepository;

    private Controller onSuccess;

    private SecurityContext securityContext;

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void setOnSuccess(Controller successController) {
        this.onSuccess = successController;
    }

    /* default */ void setSecurityContext(SecurityContext securityContext) {
        this.securityContext = securityContext;
    }

    @Override
    public void enter() {
        getUserInterface().prompt("username:");
    }

    @Override
    public Controller handle(String input) {
        if (username == null) {
            username = input;
            getUserInterface().prompt("password:");
            return this;
        } else {
            boolean loginResult = login(username, input);
            username = null;
            if (loginResult == true) {
                return onSuccess;
            } else {
                return null;
            }
        }
    }

    /* default */ boolean login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            securityContext.setUser(user);
            return user.hasPassword(password);
        }
        return false;
    }

}
